package com.wayz.service;

import com.wayz.constants.CArticleCategory;
import com.wayz.constants.CFormDataCategory;
import com.wayz.constants.PageVo;
import com.wayz.constants.ViewMap;
import com.wayz.entity.pojo.home.*;
import com.wayz.entity.vo.home.*;
import com.wayz.exception.WayzException;
import com.wayz.mapper.*;
import com.wayz.redis.BeanIdKeyEnum;
import com.wayz.redis.RedisUtils;
import com.wayz.util.CollectionUtils;
import com.wayz.util.TimeHelper;
import feign.form.FormData;
import org.apache.ibatis.annotations.Case;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

/**
 * 官网首页服务实现类
 *
 * @author mike.ma@wayz.ai
 */
@Service("homeService")
@org.apache.dubbo.config.annotation.Service(version = "1.0.0", protocol = "dubbo")
@RefreshScope
public class HomeServiceImpl implements HomeService {

    /** Redis工具 */
    @Resource(name = "redisUtils")
    private RedisUtils redisUtils = null;
    /** DAO相关 */
    /**
     * 新闻DAO接口
     */
    @Resource(name = "dArticleDAO")
    private DArticleDAO dArticleDAO = null;
    /**
     * 合作案例内容DAO
     */
    @Resource(name = "dCaseDAO")
    private DCaseDAO dCaseDAO = null;
    /**
     * 表单数据DAO
     */
    @Resource(name = "dFormDataDAO")
    private DFormDataDAO dFormDataDAO = null;
    /**
     * 省份DAO
     */
    @Resource(name = "dProvinceDAO")
    private DProvinceDAO dProvinceDAO = null;
    /**
     * 城市DAO
     */
    @Resource(name = "dCityDAO")
    private DCityDAO dCityDAO = null;

    /**
     * 查询省份
     *
     * @param myId       我的标识
     * @param provinceId 省份标识
     * @return 省份列表
     * @throws WayzException 云歌广告平台异常
     */
    @Override
    public List<ProvinceVo> queryProvince(Long myId, Long provinceId) throws WayzException {
        // 初始化
        List<ProvinceVo> provinceList = new ArrayList<ProvinceVo>();

        // 查询省份
        List<DProvince> dProvinceList = dProvinceDAO.query();

        // 转化数据
        if (dProvinceList != null) {
            for (DProvince dProvince : dProvinceList) {
                // 初始化
                ProvinceVo province = new ProvinceVo();

                // 赋值数据
                province.setId(dProvince.getId());
                province.setName(dProvince.getName());
                province.setSname(dProvince.getName());

                // 添加数据
                provinceList.add(province);
            }
        }

        // 返回数据
        return provinceList;
    }

    /**
     * 查询城市
     *
     * @param myId       我的标识
     * @param provinceId 省份标识
     * @param cityId     城市标识
     * @return 城市列表
     * @throws WayzException 云歌广告平台异常
     */
    @Override
    public List<CityVo> queryCity(Long myId, Long provinceId, Long cityId) throws WayzException {
        // 初始化
        List<CityVo> cityList = new ArrayList<CityVo>();

        // 查询城市
        List<DCity> dCityList = dCityDAO.query(provinceId);

        // 转化数据
        if (dCityList != null) {
            for (DCity dCity : dCityList) {
                // 初始化
                CityVo city = new CityVo();

                // 赋值数据
                city.setId(dCity.getId());
                city.setName(dCity.getName());

                // 添加数据
                cityList.add(city);
            }
        }

        // 返回数据
        return cityList;
    }

    /**
     * 查询新闻分类
     *
     * @param myId 我的标识
     * @return 客户视图列表
     * @throws WayzException 平台异常
     */
    @Override
    public List<ViewMap> queryArticleCategory(Long myId, Short id) throws WayzException {
        // 初始化
        List<ViewMap> articleCategoryList = new ArrayList<ViewMap>();

        // 依次转化
        for (CArticleCategory cArticleCategory : CArticleCategory.values()) {
            if (id == null || id.equals(cArticleCategory.getValue())) {
                // 初始化
                ViewMap viewMap = new ViewMap();

                // 设置参数
                viewMap.setId((long) cArticleCategory.getValue());
                viewMap.setName(cArticleCategory.getDescription());

                // 添加
                articleCategoryList.add(viewMap);
            }
        }

        // 返回数据
        return articleCategoryList;

    }

    /**
     * 创建新闻
     *
     * @param myId            我的客户标识
     * @param categoryId      分类报道
     * @param title           标题
     * @param titlePic        标题图片
     * @param description     描述
     * @param keyWords        关键词
     * @param abstractContent 摘要
     * @param content         新闻详情
     * @param pushTime        发布时间
     * @param isPush          是否发布(0=否,1=是)
     * @param sort            排序
     * @throws WayzException 平台异常
     */
    @Override
    public void createArticle(Long myId, Short categoryId, String title, String titlePic, String description,
                              String keyWords, String abstractContent, String content, String pushTime, Boolean isPush, Integer sort)
            throws WayzException {
        // 校验
        if (dArticleDAO.existTitle(title)) {
            throw new WayzException("标题已存在");
        }

        // 初始化
        DArticle dArticleCreate = new DArticle();

        // 设置参数
        // long id = new IdWorker().getId();
        Long id = redisUtils.incrBy(BeanIdKeyEnum.WEBSITE_ARTICLE.getKey(), RedisUtils.STEP_SIZE);
        dArticleCreate.setCategoryId(categoryId);
        dArticleCreate.setTitle(title);
        dArticleCreate.setTitlePic(titlePic);
        dArticleCreate.setDescription(description);
        dArticleCreate.setKeyWords(keyWords);
        dArticleCreate.setAbstractContent(abstractContent);
        dArticleCreate.setContent(content);
        dArticleCreate.setIsPush(isPush);
        dArticleCreate.setSort(sort);
        Timestamp time = TimeHelper.getTimestamp(TimeHelper.getDate(pushTime).getTime());
        dArticleCreate.setPushTime(time);

        // 创建
        dArticleDAO.create(id, dArticleCreate);

        // 读取HTML模板生成HTML页面
        // JspToNewsHtmlFile(title, keyWords, description, titlePic, content,
        // abstractContent, pushTime, id);
    }

    /**
     * 修改新闻
     *
     * @param myId            我的客户标识
     * @param id              标识
     * @param categoryId      分类报道
     * @param title           标题
     * @param titlePic        标题图片
     * @param description     描述
     * @param keyWords        关键词
     * @param abstractContent 摘要
     * @param content         新闻详情
     * @param pushTime        发布时间
     * @param isPush          是否发布(0=否,1=是)
     * @param sort            排序
     * @throws WayzException 平台异常
     */
    @Override
    public void modifyArticle(Long myId, Long id, Short categoryId, String title, String titlePic, String description,
                              String keyWords, String abstractContent, String content, String pushTime, Boolean isPush, Integer sort)
            throws WayzException {
        // 校验
        DArticle dArticle = dArticleDAO.get(id);
        if (dArticle == null) {
            throw new WayzException("新闻不存在");
        }

        // 初始化
        DArticle dArticleModify = new DArticle();

        // 赋值
        dArticleModify.setId(id);
        dArticleModify.setCategoryId(categoryId);
        dArticleModify.setTitle(title);
        dArticleModify.setTitlePic(titlePic);
        dArticleModify.setDescription(description);
        dArticleModify.setKeyWords(keyWords);
        dArticleModify.setAbstractContent(abstractContent);
        dArticleModify.setContent(content);
        dArticleModify.setIsPush(isPush);
        dArticleModify.setSort(sort);
        Timestamp time = TimeHelper.getTimestamp(TimeHelper.getDate(pushTime).getTime());
        dArticleModify.setPushTime(time);

        // 修改
        dArticleDAO.modify(dArticleModify);

        // 读取HTML模板生成HTML页面
        // JspToNewsHtmlFile(title, keyWords, description, titlePic, content,
        // abstractContent, pushTime, id);
    }

    /**
     * 删除新闻
     *
     * @param myId 我的客户标识
     * @param id   标识
     * @throws WayzException 平台异常
     */
    @Override
    public void delArticle(Long myId, Long id) throws WayzException {
        // 校验
        DArticle dArticle = dArticleDAO.get(id);
        if (dArticle == null) {
            throw new WayzException("新闻不存在");
        }
        // 初始化
        DArticle dArticleModify = new DArticle();

        // 赋值
        dArticleModify.setId(id);
        dArticleModify.setIsDel(true);

        // 修改
        dArticleDAO.modify(dArticleModify);
    }

    /**
     * 修改发布
     *
     * @param myId 我的客户标识
     * @param id   标识
     * @throws WayzException 平台异常
     */
    @Override
    public void modifyArticlePush(Long myId, Long id) throws WayzException {
        // 校验
        DArticle dArticle = dArticleDAO.get(id);
        if (dArticle == null) {
            throw new WayzException("新闻不存在");
        }

        // 初始化
        DArticle dArticleModify = new DArticle();

        // 赋值
        dArticleModify.setId(id);
        if (dArticle.getIsPush()) {
            dArticleModify.setIsPush(false);
        } else {
            dArticleModify.setIsPush(true);

        }
        dArticleDAO.modify(dArticleModify);
    }

    /**
     * 查询发布
     *
     * @param myId       我的客户标识
     * @param categoryId 分类报道
     * @param title      标题
     * @param isPush     是否发布(0=否,1=是)
     * @return 新闻分页
     * @throws WayzException 平台异常
     */
    @Override
    public PageVo<ArticleVo> queryArticle(Long myId, Short categoryId, String title, Boolean isPush, Integer startIndex,
                                          Integer pageSize) throws WayzException {
        // 初始化
        PageVo<ArticleVo> page = new PageVo<>();
        List<ArticleVo> articleList = new ArrayList<ArticleVo>(); //Lists.newArrayList();

        // 查询
        Integer totalCount = dArticleDAO.count(categoryId, title, isPush);
        if (totalCount <= 0) {
            return page;
        }

        List<DArticle> dArticleList = dArticleDAO.query(categoryId, title, isPush, startIndex, pageSize);
        if (CollectionUtils.isNotEmpty(dArticleList)) {
            for (DArticle dArticle : dArticleList) {
                ArticleVo article = new ArticleVo();
                article.setId(dArticle.getId());
                article.setCategoryId(dArticle.getCategoryId());
                article.setCategoryName(CArticleCategory.getDescription(dArticle.getCategoryId()));
                article.setTitle(dArticle.getTitle());
                article.setTitlePic(dArticle.getTitlePic());
                article.setPushTime(TimeHelper.getDate(TimeHelper
                        .getDate(new Date(dArticle.getPushTime().getTime()), 0)));
                article.setIsPush(dArticle.getIsPush());
                article.setSort(dArticle.getSort());
                article.setCreatedTime(TimeHelper.getTimestamp(dArticle.getCreatedTime()));
                article.setAbstractContent(dArticle.getAbstractContent());
                if (dArticle.getModifiedTime() != null) {
                    article.setModifiedTime(TimeHelper.getTimestamp(dArticle.getModifiedTime()));

                }
                articleList.add(article);
            }
        }
        // 赋值
        page.setTotalCount(totalCount);
        page.setList(articleList);

        // 返回数据
        return page;
    }

    /**
     * 新闻详情
     *
     * @param myId 我的客户标识
     * @param id   标识
     * @return 新闻详情
     * @throws WayzException 平台异常
     */
    @Override
    public ArticleVo getArticle(Long myId, Long id) throws WayzException {
        // 校验
        DArticle dArticle = dArticleDAO.get(id);
        if (dArticle == null) {
            throw new WayzException("新闻不存在");
        }

        // 初始化
        ArticleVo article = new ArticleVo();
        article.setId(dArticle.getId());
        article.setCategoryId(dArticle.getCategoryId());
        article.setCategoryName(CArticleCategory.getDescription(dArticle.getCategoryId()));
        article.setTitle(dArticle.getTitle());
        article.setKeyWords(dArticle.getKeyWords());
        article.setTitlePic(dArticle.getTitlePic());
        article.setPushTime(TimeHelper.getDate(TimeHelper.getDate(new Date(dArticle.getPushTime().getTime()), 0)));
        article.setAbstractContent(dArticle.getAbstractContent());
        article.setContent(dArticle.getContent());
        article.setIsPush(dArticle.getIsPush());
        article.setSort(dArticle.getSort());
        article.setDescription(dArticle.getDescription());
        article.setCreatedTime(TimeHelper.getTimestamp(dArticle.getCreatedTime()));
        if (dArticle.getModifiedTime() != null) {
            article.setModifiedTime(TimeHelper.getTimestamp(dArticle.getModifiedTime()));

        }
        // 返回数据
        return article;
    }

    /**
     * 获取合作案例
     *
     * @param id 案例标识
     * @return 合作案例
     * @throws WayzException 平台异常
     */
    @Override
    public CaseVo getCase(Long id) throws WayzException {
        // 校验
        DCase dCase = dCaseDAO.get(id);
        if (dCase == null) {
            throw new WayzException("合作案例不存在");
        }

        // 初始化
        CaseVo bean = new CaseVo();

        // 设置参数
        bean.setId(id);
        bean.setTitle(dCase.getTitle());
        bean.setSubTitle(dCase.getSubTitle());
        bean.setTitlePic(dCase.getTitlePic());
        bean.setImgUrl(dCase.getImgUrl());
        bean.setSeoTitle(dCase.getSeoTitle());
        bean.setKeyWords(dCase.getKeyWords());
        bean.setDescription(dCase.getDescription());
        bean.setContent(dCase.getContent());
        bean.setPushTime(dCase.getPushTime());
        bean.setIsPush(dCase.getIsPush());
        bean.setSort(dCase.getSort());
        bean.setCreatedTime(TimeHelper.getTimestamp(dCase.getCreatedTime()));
        bean.setModifiedTime(TimeHelper.getTimestamp(dCase.getModifiedTime()));

        // 返回数据
        return bean;
    }

    /**
     * 查询合作案例
     *
     * @param title  标题名称(模糊查询)
     * @return 合作案例分页
     * @throws WayzException 平台异常
     */
    @Override
    public PageVo<CaseVo> queryCase(String title, Boolean isPush, Integer startIndex, Integer pageSize) throws WayzException {
		// 初始化
		PageVo<CaseVo> page = new PageVo<>();
		List<CaseVo> caseList = new ArrayList<CaseVo>(); //Lists.newArrayList();

		// 查询
		Integer totalCount = dCaseDAO.count(title, isPush);
		if (totalCount <= 0) {
			return page;
		}
        List<DCase> dCaseList = dCaseDAO.query(title, isPush, startIndex, pageSize);

        // 依次转化
        if (dCaseList != null && dCaseList.size() > 0) {
            for (DCase dCase : dCaseList) {
                // 初始化
                CaseVo bean = new CaseVo();

                // 设置参数
                bean.setId(dCase.getId());
                bean.setTitle(dCase.getTitle());
                bean.setSubTitle(dCase.getSubTitle());
                bean.setTitlePic(dCase.getTitlePic());
                bean.setImgUrl(dCase.getImgUrl());
                bean.setSeoTitle(dCase.getSeoTitle());
                bean.setKeyWords(dCase.getKeyWords());
                bean.setDescription(dCase.getDescription());
                bean.setContent(dCase.getContent());
                bean.setPushTime(dCase.getPushTime());
                bean.setIsPush(dCase.getIsPush());
                bean.setSort(dCase.getSort());
                bean.setCreatedTime(TimeHelper.getTimestamp(dCase.getCreatedTime()));
                if (dCase.getModifiedTime() != null) {
                    bean.setModifiedTime(TimeHelper.getTimestamp(dCase.getModifiedTime()));
                }
                // 添加
                caseList.add(bean);
            }

            // 赋值
			page.setList(caseList);
			page.setTotalCount(totalCount);
        }

        // 返回数据
        return page;
    }

    /**
     * 修改合作案例
     *
     * @param myId        我的客户标识
     * @param id          案例标识
     * @param title       标题
     * @param subTitle    副标题
     * @param titlePic    标题图片url
     * @param imgUrl      列表图片url
     * @param seoTitle    seo标题
     * @param keyWords    关键字
     * @param description 描述
     * @param content     新闻详情
     * @param pushTime    发布时间
     * @param isPush      是否发布(0=否,1=是)
     * @param sort        排序
     * @throws WayzException 平台异常
     */
    @Override
    public void modifyCase(Long myId, Long id, String title, String subTitle, String titlePic, String imgUrl,
                           String seoTitle, String keyWords, String description, String content, String pushTime, Boolean isPush,
                           Integer sort) throws WayzException {
        // 获取
        DCase dCase = dCaseDAO.get(id);
        if (dCase == null) {
            throw new WayzException("合作案例不存在");
        }
        if (!dCase.getTitle().equals(title) && dCaseDAO.getByTitle(title) != null) {
            throw new WayzException("合作案例标题已存在");
        }

        // 初始化
        DCase dCaseModify = new DCase();

        // 设置
        dCaseModify.setId(id);
        dCaseModify.setTitle(title);
        dCaseModify.setSubTitle(subTitle);
        dCaseModify.setTitlePic(titlePic);
        dCaseModify.setImgUrl(imgUrl);
        dCaseModify.setSeoTitle(seoTitle);
        dCaseModify.setKeyWords(keyWords);
        dCaseModify.setDescription(description);
        dCaseModify.setContent(content);
        dCaseModify.setPushTime(pushTime);
        dCaseModify.setIsPush(isPush);
        dCaseModify.setSort(sort);

        // 修改
        dCaseDAO.modify(dCaseModify);

        // 读取HTML模板生成HTML页面
        // JspToCaseHtmlFile(title, keyWords, description, name, fileUrl,
        // imgUrl, abstractContent, getCaseListHtml(typeId), id);
    }

    /**
     * 创建合作案例
     *
     * @param myId        我的客户标识
     * @param title       标题
     * @param subTitle    副标题
     * @param titlePic    标题图片url
     * @param imgUrl      列表图片url
     * @param seoTitle    seo标题
     * @param keyWords    关键字
     * @param description 描述
     * @param content     新闻详情
     * @param pushTime    发布时间
     * @param isPush      是否发布(0=否,1=是)
     * @param sort        排序
     * @throws WayzException 平台异常
     */
    @Override
    public void createCase(Long myId, String title, String subTitle, String titlePic, String imgUrl, String seoTitle,
                           String keyWords, String description, String content, String pushTime, Boolean isPush, Integer sort)
            throws WayzException {
        if (dCaseDAO.getByTitle(title) != null) {
            throw new WayzException("合作案例标题已存在");
        }

        // 初始化
		DCase dCaseCreate = new DCase();

        // 设置
        Long id = redisUtils.incrBy(BeanIdKeyEnum.WEBSITE_CASE.getKey(), RedisUtils.STEP_SIZE);
        dCaseCreate.setTitle(title);
        dCaseCreate.setSubTitle(subTitle);
        dCaseCreate.setTitlePic(titlePic);
        dCaseCreate.setImgUrl(imgUrl);
        dCaseCreate.setSeoTitle(seoTitle);
        dCaseCreate.setKeyWords(keyWords);
        dCaseCreate.setDescription(description);
        dCaseCreate.setContent(content);
        dCaseCreate.setPushTime(pushTime);
        dCaseCreate.setIsPush(isPush);
        dCaseCreate.setSort(sort);

        // 创建
        dCaseDAO.create(id, dCaseCreate);

        // 读取HTML模板生成HTML页面
        // JspToCaseHtmlFile(title, keyWords, description, name, fileUrl,
        // imgUrl, abstractContent, getCaseListHtml(typeId), id);
    }

    /**
     * 删除合作案例
     *
     * @param myId 我的客户标识
     * @param id   案例标识
     * @throws WayzException 平台异常
     */
    @Override
    public void deleteCase(Long myId, Long id) throws WayzException {
        // 获取
        DCase dCase = dCaseDAO.get(id);
        if (dCase == null) {
            throw new WayzException("合作案例不存在");
        }

        // 初始化
		DCase dCaseModify = new DCase();

        // 设置
        dCaseModify.setId(id);
        dCaseModify.setIsDel(true);

        // 修改
        dCaseDAO.modify(dCaseModify);
        // dCaseDAO.delete(id);
    }

    /**
     * 发布合作案例
     *
     * @param myId 我的客户标识
     * @param id   案例标识
     * @throws WayzException 平台异常
     */
    @Override
    public void modifyCasePush(Long myId, Long id) throws WayzException {
        DCase dCase = dCaseDAO.get(id);
        if (dCase == null) {
            throw new WayzException("合作案例不存在");
        }
        DCase dCaseModify = new DCase();
        dCaseModify.setId(id);
        if (dCase.getIsPush()) {
            dCaseModify.setIsPush(false);
        } else {
            dCaseModify.setIsPush(true);

        }
        dCaseDAO.modify(dCaseModify);
    }

    /**
     * 查询表单数据
     *
     * @param myId
     * @param type        类型
     * @param companyName 公司名称
     * @param phone       手机号
     * @param startIndex  开始序号
     * @param pageSize    页面大小
     * @return platform应答
     * @throws WayzException 平台异常
     */
    @Override
    public PageVo<FormDataVo> queryFormData(Long myId, Short type, Long provinceId, Long cityId, String companyName,
											String phone, Integer startIndex, Integer pageSize) throws WayzException {
		// 初始化
		PageVo<FormDataVo> page = new PageVo<>();
		List<FormDataVo> formDataList = new ArrayList<FormDataVo>(); //Lists.newArrayList();

		// 查询
		Integer totalCount = dFormDataDAO.count(type, provinceId, cityId, companyName, phone);
		if (totalCount <= 0) {
			return page;
		}
        List<DFormData> dFormDataList = dFormDataDAO.query(type, provinceId, cityId, companyName, phone, startIndex,
                pageSize);
        if (CollectionUtils.isNotEmpty(dFormDataList)) {
            for (DFormData dFormData : dFormDataList) {
				FormDataVo formData = new FormDataVo();
                formData.setId(dFormData.getId());
                formData.setType(dFormData.getType());
                formData.setProvinceName(dFormData.getProvinceName());
                formData.setCityName(dFormData.getCityName());
                formData.setCompanyName(dFormData.getCompanyName());
                formData.setTelephone(dFormData.getTelephone());
                formData.setContact(dFormData.getContact());
                formData.setTypeName(CFormDataCategory.getDescription(dFormData.getType()));
                formData.setAddress(dFormData.getAddress());
                formData.setCreatedTime(TimeHelper.getTimestamp(dFormData.getCreatedTime()));
                formDataList.add(formData);
            }
        }

        page.setTotalCount(totalCount);
        page.setList(formDataList);

        // 返回数据
        return page;
    }

    /**
     * 查询表单数据分类
     *
     * @param myId 我的标识
     * @return 表单数据视图列表
     * @throws
     */
    @Override
    public List<ViewMap> queryFormDataCategory(Long myId, Short id) throws WayzException {
        // 初始化
        List<ViewMap> categoryList = new ArrayList<ViewMap>();

        // 依次转化
        for (CFormDataCategory cCategory : CFormDataCategory.values()) {
            if (id == null || id.equals(cCategory.getValue())) {
                // 初始化
                ViewMap viewMap = new ViewMap();

                // 设置参数
                viewMap.setId((long) cCategory.getValue());
                viewMap.setName(cCategory.getDescription());

                // 添加
                categoryList.add(viewMap);
            }
        }

        // 返回数据
        return categoryList;
    }

}
